<?php

include_once dirname(__FILE__) . '/Customer.php';

class Group {

    public $group_id;
    public $group_name;

    //构造函数
    private function __construct($id) {
        $db = Db::get_instance();
        $sql = "SELECT * FROM  fac_group where group_id=" . $id;
        $rs = $db->query($sql);
        $row = $rs[0];
        $this->group_id = $row['group_id'];
        $this->group_name = $row['group_name'];
        //print $group_name;
    }

    //把字段更新到数据库
    public function update() {
        $sql = 'UPDATE fac_group set group_name=\'' . $this->group_name . '\' where group_id=' . $this->group_id;
        return Db::get_instance()->query($sql);
    }

    //生产一个Group对象,
    public static function get_a_group($id) {  //传入一个id
        $id = intval($id);
        if (Group::is_id_Exist($id))
            return new Group($id);
        else
            return null;
    }

    //根据id判断分组是否存在
    public static function is_id_Exist($id) {
        $sql = 'SELECT count(*) as num from fac_group where group_id=' . $id;
        //echo 'sql='.$sql;
        $rs = Db::get_instance()->query($sql);
        return $rs[0]['num'] > 0;
    }

    //得到分组列表
    public static function get_groups() {
        return Db::get_instance()->query("SELECT * FROM `fac_group`;");
    }

    //删除一个分组,分组与客户之间是级联删除，所以这里可以直接删除
    public static function delete($id) {
        $id = intval($id);
        if (Group::is_id_Exist($id)) {
            $sql = "delete from fac_group where group_id=" . $id;
            return Db::get_instance()->query($sql);
        } else
            return false;
    }

    //增加一个分组
    public static function add_a_group($name) {
        $sql = 'INSERT INTO fac_group(group_name) value (\'' . $name . '\')';
        return Db::get_instance()->query($sql);
    }

}
